package tech.summerly.weather.util

import android.arch.persistence.room.TypeConverter
import android.location.Location
import android.os.Parcel
import android.os.Parcelable
import java.util.*
import kotlin.math.roundToInt

/**
 * 位置
 *
 * @param longitude 经度
 * @param latitude 纬度
 */
data class Position(val longitude: Double, val latitude: Double) : Parcelable {

    /**
     * 计算两个位置间的距离
     *
     * @return meters
     */
    fun distanceTo(another: Position): Float {
        val array = FloatArray(1)
        Location.distanceBetween(latitude, longitude, another.latitude, another.longitude, array)
        return array[0]
    }

    fun stringify(): String {
        return "$longitude,$latitude"
    }

    constructor(source: Parcel) : this(
            source.readDouble(),
            source.readDouble()
    )

    override fun describeContents() = 0

    override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
        writeDouble(longitude)
        writeDouble(latitude)
    }

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<Position> = object : Parcelable.Creator<Position> {
            override fun createFromParcel(source: Parcel): Position = Position(source)
            override fun newArray(size: Int): Array<Position?> = arrayOfNulls(size)
        }
    }
}


fun Float.toIntString() = if (isNaN()) "NaN" else roundToInt().toString()

/**
 * 将形如 2018-03-15 的字符串解析出来
 */
fun String.formatDate(): Calendar {
    val calendar = Calendar.getInstance()
    val year = this.substring(0, 4).toInt()
    val month = this.substring(5, 7).toInt() - /*calendar 的月份是以 0 开始的.*/1
    val day = this.substring(8, 10).toInt()
    calendar.set(year, month, day)
    return calendar
}

fun Calendar.isToday(): Boolean {
    val calendar = this
    val today = Calendar.getInstance()
    today.time = Date(System.currentTimeMillis())
    return today.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)
            && today.get(Calendar.DAY_OF_YEAR) == calendar.get(Calendar.DAY_OF_YEAR)
}

fun Calendar.getWeekDay(): String = when (get(Calendar.DAY_OF_WEEK)) {
    Calendar.SUNDAY -> "周日"
    Calendar.MONDAY -> "周一"
    Calendar.TUESDAY -> "周二"
    Calendar.WEDNESDAY -> "周三"
    Calendar.THURSDAY -> "周四"
    Calendar.FRIDAY -> "周五"
    Calendar.SATURDAY -> "周六"
    else -> "Na"
}

class PositionConverter {
    companion object {
        private const val POSITION_SEPARATOR = ','
    }

    @TypeConverter
    fun parseToPosition(str: String): Position {
        val lon = str.substringBefore(POSITION_SEPARATOR).toDouble()
        val lat = str.substringAfter(POSITION_SEPARATOR).toDouble()
        return Position(lon, lat)
    }

    @TypeConverter
    fun postionToString(position: Position): String = position.stringify()
}